package com.app.micaihu.receiver;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.view.main.DispatchActivity;
import com.baidu.mobstat.MtjConfig;
import com.google.gson.Gson;
import com.xiaomi.mipush.sdk.ErrorCode;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.xiaomi.mipush.sdk.MiPushCommandMessage;
import com.xiaomi.mipush.sdk.MiPushMessage;
import com.xiaomi.mipush.sdk.PushMessageReceiver;

import java.util.List;

/**
 * Created by Guo on 2016/8/8.
 * <p/>
 * 小米推送的广播接受者
 * 以下方法均运行在非UI线程
 */
public class MiPushMessageReceiver extends PushMessageReceiver {

    private String mRegId;

    /**
     * 用来接收服务器发送的透传消息
     *
     * @param context
     * @param miPushMessage
     */
    @Override
    public void onReceivePassThroughMessage(Context context, MiPushMessage miPushMessage) {
        String content = miPushMessage.getContent();
        int passThrough = miPushMessage.getPassThrough();
        if (passThrough == 1) {//类型1 是透传;
            NewsEntity newsEntity = null;
            try {
                Gson gson = new Gson();
                newsEntity = gson.fromJson(content, NewsEntity.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (newsEntity != null) {
                String showType = newsEntity.getShowType();
                if (TextUtils.equals(showType, TypeConstant.PUSH_FOCUSNEWS)) {
                    //当前app运行并且在聚焦页面
//                    if (IPushManager.getInstance().isAppIsInBackground(context)) {
//                        Activity lastActivity = AppManager.getAppManager().getLastActivity();
//                        if (lastActivity instanceof MainActivity) {//TODO 还要判断当前是聚焦界面
////                            IPushManager.getInstance().showFoucsDialog(lastActivity, newsEntity, TypeConstant.PUSHTYPE_XIAOMI);
//                            boolean currentFragment = ((MainActivity) lastActivity).getCurrentFragment();
//
//
//                        }
//                    } else {//记录到本地
                    AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.push_foucusnews, content + "}_" + System.currentTimeMillis() + "}_" + TypeConstant.PUSHTYPE_XIAOMI);
                    AppConfigTools.isShowPushDialog = true;
//                    }
                }
                //IPushManager.getInstance().showNotification(AppApplication.getInstance(),newsEntity,TypeConstant.PUSHTYPE_XIAOMI);
            }
        }

    }

    /**
     * 用来接收服务器发来的通知栏消息（用户点击通知栏时触发）
     *
     * @param context
     * @param miPushMessage
     */
    @Override
    public void onNotificationMessageClicked(Context context, MiPushMessage miPushMessage) {
        //super.onNotificationMessageClicked(context, miPushMessage);
        String content = miPushMessage.getContent();
        int passThrough = miPushMessage.getPassThrough();
        if (!TextUtils.isEmpty(content)) {
            if (passThrough == 0) {//类型0 是通知栏
                NewsEntity newsEntity = null;
                try {
                    Gson gson = new Gson();
                    newsEntity = gson.fromJson(content, NewsEntity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (newsEntity != null && !TextUtils.isEmpty(newsEntity.getArticleId()) && !TextUtils.isEmpty(newsEntity.getArticleType())) {

                    String articleId = newsEntity.getArticleId();
                    String articleType = newsEntity.getArticleType();
                    String pushType = TypeConstant.PUSHTYPE_XIAOMI;

                    Intent intent = new Intent();
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.putExtra(Config.Extra.PARAMETER1, articleId);
                    intent.putExtra(Config.Extra.PARAMETER2, articleType);
                    intent.putExtra(TypeConstant.PUSH_TYPE, pushType);
                    // 百度统计 启动来源推送 来源统计
                    intent.putExtra(MtjConfig.BAIDU_MTJ_PUSH_CALL, true);
                    // 建议添加，如果是敏感信息，可以不添加，则报表上也就无法展现
                    intent.putExtra(MtjConfig.BAIDU_MTJ_PUSH_MSG, newsEntity.getArticleTitle());
                    if (!TextUtils.isEmpty(newsEntity.getJumpUrl())) {
                        intent.putExtra("url", newsEntity.getJumpUrl());
                    }

                    if (!TextUtils.isEmpty(newsEntity.getSerialId())) {
                        intent.putExtra("serialId", newsEntity.getSerialId());
                    }

                    intent.putExtra(DispatchActivity.PUSH_OR_WAKEUP, true);
                    intent.setClass(context, DispatchActivity.class);

                    context.startActivity(intent);


//                    String articleId = newsEntity.getArticleId();
//                    String articleType = newsEntity.getArticleType();
//                    Intent intent = new Intent();
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent.putExtra(BaseActivity.PARAMETER1, articleId);
//                    intent.putExtra(BaseActivity.PARAMETER2, TypeConstant.SOURCETYPE_PUSH);
//                    intent.putExtra(TypeConstant.PUSH_TYPE, TypeConstant.PUSHTYPE_XIAOMI);
//
//                    switch (articleType) {
//                        //适配所有文章
//                        case TypeConstant.NEWS_NORMAL:
//                        case TypeConstant.NEWS_WEB:
//                        case TypeConstant.NEWS_SHOP:
//                            intent.setClass(context, NewsDetailActivity.class);
//                            StatService.onEvent(context, "054", "新闻", 1);// 统计的点击的次数
//                            break;
//                        case TypeConstant.NEWS_SHOP_WEB://电商网页文章
//                            intent.setClass(context, WebActivity.class);
//                            intent.putExtra("url", newsEntity.getJumpUrl());
//                            StatService.onEvent(context, "054", "电商软文", 1);// 统计的点击的次数
//                            break;
//                        //适配图库
//                        case TypeConstant.PIC_NORMAL:
//                            intent.setClass(context, ImageDetailActivity.class);
//                            StatService.onEvent(context, "054", "图库", 1);// 统计的点击的次数
//                            break;
//                        //适配图库轻专题
//                        case TypeConstant.PIC_TOPIC:
//                            //待开发
//                            break;
//                        //普通视频
//                        case TypeConstant.VIDEO_NORMAL:
//                        case TypeConstant.VIDEO_ORIGINAL:    //原创视频
//                            intent.setClass(context, VideoDetailActivity.class);
//                            StatService.onEvent(context, "054", "视频", 1);// 统计的点击的次数
//                            break;
//
////                        case TypeConstant.TOPIC_POST://话题
//                        case TypeConstant.POST_2052:
//                             intent.setClass(context, PostDetailActivity.class);
//                            StatService.onEvent(context, "054", "话题", 1);// 统计的点击的次数
//
//                            break;
//
//                        case TypeConstant.NEWS_TOPIC://新闻专辑
//                            intent.setClass(context, NewsTopicsActivity.class);
//                            StatService.onEvent(context, "054", "新闻专辑", 1);// 统计的点击的次数
//                            break;
//
//                        case TypeConstant.PUSH_COMMENT://推送的评论
//                            intent.setClass(context, MainActivity.class);
//                            intent.putExtra(BaseActivity.PARAMETER2, TypeConstant.PUSH_COMMENT);
//                            StatService.onEvent(context, "054", "评论", 1);// 统计的点击的次数
//                            break;
//                        case TypeConstant.ONLY_URL://推送 前文webActivity
//                            intent.setClass(context, WebActivity.class);
//                            intent.putExtra("url", newsEntity.getJumpUrl());
//                            StatService.onEvent(context, "054", "直接打开URL", 1);// 统计的点击的次数
//                            break;
//
//                    }
//
//                    if (intent.getComponent() != null) {
//                        if (!AppManager.getAppManager().isHaveActivity(MainActivity.class)) {//当前栈中没有MainActivity
//                            intent.putExtra(BaseActivity.PARAMETER2, articleType);
//                            intent.setClass(context, LunchActivity.class);
//                        }
//                        AppApplication.getInstance().startActivity(intent);
//                    }

                }
            }
        }
    }

    /**
     * 用来接收服务器发来的通知栏消息（消息到达客户端时触发，并且可以接收应用在前台时不弹出通知的通知消息）
     *
     * @param context
     * @param miPushMessage
     */
    @Override
    public void onNotificationMessageArrived(Context context, MiPushMessage miPushMessage) {
        String content = miPushMessage.getContent();
        //super.onNotificationMessageArrived(context, miPushMessage);
       /* String content = miPushMessage.getContent();
        Log.e("gzq","到达content="+content);
        Map<String, String> extra = miPushMessage.getExtra();
        String payload = extra.get("payload");
        int passThrough = miPushMessage.getPassThrough();
        Log.e("gzq","到达---payload="+payload+"---passThrough="+passThrough);*/
    }

    /**
     * 用来接受客户端向服务器发送注册命令消息后返回的响应
     *
     * @param context
     * @param miPushCommandMessage
     */
    @Override
    public void onReceiveRegisterResult(Context context, MiPushCommandMessage miPushCommandMessage) {
//        super.onReceiveRegisterResult(context, miPushCommandMessage);
        String command = miPushCommandMessage.getCommand();

        List<String> arguments = miPushCommandMessage.getCommandArguments();

        String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null);
       /* for(int i = 0;i<arguments.size();i++){
            LogUtils.e("gzq","cmdArg="+arguments.get(i));
        }
*/
        String log;
        if (MiPushClient.COMMAND_REGISTER.equals(command)) {
            if (miPushCommandMessage.getResultCode() == ErrorCode.SUCCESS) {
                mRegId = cmdArg1;
            } else {
            }
        } else if (MiPushClient.COMMAND_SUBSCRIBE_TOPIC.equals(command)) {

        } else {
        }
        String regId = MiPushClient.getRegId(AppApplication.getInstance());
        AppConfigManager.getInstance().writeConfig(UserConfigTools.XIAOMI_REGID, regId);
    }

    /**
     * 用来接收客户端向服务器发送命令消息后返回的响应
     *
     * @param context
     * @param miPushCommandMessage
     */
    @Override
    public void onCommandResult(Context context, MiPushCommandMessage miPushCommandMessage) {
        super.onCommandResult(context, miPushCommandMessage);
    }


}
